/*
 * @Author: your name
 * @Date: 2022-03-16 20:51:30
 * @LastEditTime: 2022-04-03 20:14:25
 * @LastEditors: Please set LastEditors
 * @Description: 通用分类树形结构
 * @FilePath: \blog-system-front\src\components\CategoryTreeSelect\index.js
 */
import React, { useEffect, useState } from "react";
import { Tree } from "antd";

export default function CategoryTreeSelect(props) {
  const { onSelect, category, checkbox } = props;
  const [treeData, setTreeData] = useState([]);
  const renderChildren = (data, item) => {
    const renderData = [];
    const children = data.filter((n) => n.parentId === item.category_id);
    if (children.length !== 0) {
      children.forEach((d) =>
        renderData.push({
          ...d,
          children: renderChildren(data, d),
        })
      );
    }

    return renderData;
  };

  /**
   * @description: 处理树组件所需结构
   * @param {*} data --- 树形结构数据
   * @return {*}
   */
  const handleTreeOption = (data) => {
    return data.map((d) => {
      if (d.children && d.children.length !== 0) {
        return {
          key: d.category_id,
          title: d.category_name,
          children: handleTreeOption(d.children),
        };
      }
      return {
        key: d.category_id,
        title: d.category_name,
        children: [],
      };
    });
  };
  useEffect(() => {
    const data = handleTreeOption(category);
    setTreeData(data);
  }, [category]);
  return <Tree onSelect={onSelect} treeData={treeData} multiple={checkbox} />;
}
